package com.aos.erp.fs.web.rest;

import com.aos.erp.common.GlobalConstant;
import com.aos.erp.common.bean.ResultEntity;
import com.aos.erp.common.exception.BizException;
import com.aos.erp.fs.model.LayUIFileDTO;
import com.aos.erp.fs.model.LayUIResult;
import com.aos.erp.fs.model.SysFile;
import com.aos.erp.fs.service.SysFileService;
import com.aos.erp.fs.storage.FileStorageAdapter;
import com.aos.erp.fs.web.Base64MultipartFile;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

@Slf4j
@Controller("SysFileUploadController")
@Api("文件上传")
public class SysFileUploadController {
    @Value("${spring.application.name:erp-file-service}")
    private String currentServerName;

    @Resource
    private SysFileService fileService;
    @Resource
    private FileStorageAdapter fileStorageAdapter;

    @PostMapping("/file/upload")
    @ResponseBody
    @ApiOperation(value = "文件上传", authorizations = @Authorization("TOKEN"))
    @ApiImplicitParams({   @ApiImplicitParam(name = "appId", required = true, paramType = "form")})
    public ResultEntity<Long> upload(@RequestParam("file") MultipartFile file, @RequestParam("appId") String appId, @RequestParam("currentUserId") String currentUserId) throws BizException {

        //遍历并保存文件
        if (file != null && file.getSize() > 0) {
            SysFile bean = new SysFile();
            //公共属性设置
            bean.setAppId(appId);
            bean.setUserId(currentUserId);
            bean.setSize(file.getSize());
            bean.setName(file.getOriginalFilename());
            bean.setType(file.getContentType());

            //存储在阿里云
            boolean saved = fileStorageAdapter.save(bean, file, "1");
            if (saved) {
                fileService.addBean(bean);
                return ResultEntity.success().setData(bean.getId());
            } else {
                return ResultEntity.failed("文件保存失败");
            }
        }

        return ResultEntity.failed("文件不能为空");
    }

    @PostMapping(GlobalConstant.GATEWAY_IGNORE+"/file/upload")
    @ResponseBody
    @ApiOperation(value = "文件上传", authorizations = @Authorization("TOKEN"))
    @ApiImplicitParams({   @ApiImplicitParam(name = "appId", required = true, paramType = "form")
            , @ApiImplicitParam(name = "phone", required = true, paramType = "form")})
    public ResultEntity<Long> uploadWithIgnore(@RequestParam("file") MultipartFile file, @RequestParam("appId") String appId, @RequestParam("phone") String phone) throws BizException {

        //遍历并保存文件
        if (file != null && file.getSize() > 0) {
            SysFile bean = new SysFile();
            //公共属性设置
            bean.setAppId(appId);
            bean.setUserId(phone);
            bean.setSize(file.getSize());
            bean.setName(file.getOriginalFilename());
            bean.setType(file.getContentType());

            //存储在阿里云
            boolean saved = fileStorageAdapter.save(bean, file, "1");
            if (saved) {
                fileService.addBean(bean);
                return ResultEntity.success().setData(bean.getId());
            } else {
                return ResultEntity.failed("文件保存失败");
            }
        }

        return ResultEntity.failed("文件不能为空");
    }


    @PostMapping(GlobalConstant.GATEWAY_IGNORE+"/file/uploadByLayUI")
    @ResponseBody
    @ApiOperation(value = "文件上传", authorizations = @Authorization("TOKEN"))
    @ApiImplicitParams({  @ApiImplicitParam(name = "appId", required = true, paramType = "form")})
    public LayUIResult<LayUIFileDTO> uploadByLayUI(@RequestParam("file") MultipartFile file, @RequestParam("appId") String appId, @RequestParam("currentUserId") String currentUserId) throws BizException {
        LayUIResult<LayUIFileDTO> re = new LayUIResult<LayUIFileDTO>();
        //遍历并保存文件
        if (file != null && file.getSize() > 0) {
            SysFile bean = new SysFile();
            //公共属性设置
            bean.setAppId(appId);
            bean.setUserId(currentUserId);
            bean.setSize(file.getSize());
            bean.setName(file.getOriginalFilename());
            bean.setType(file.getContentType());

            boolean saved = fileStorageAdapter.save(bean, file, "1");
            if (saved) {
                fileService.addBean(bean);
                LayUIFileDTO fileDTO = new LayUIFileDTO();
                fileDTO.setSrc("/" + currentServerName.toUpperCase() + "/file/show?id=" + bean.getId());
                fileDTO.setTitle(bean.getName());
                re.setData(fileDTO);
            } else {
                re.setCode("-1");
                re.setMsg("文件保存失败");
            }
        } else {
            re.setCode("-1");
            re.setMsg("文件不能为空");
        }

        return re;
    }

    @PostMapping("/file/saveBase64")
    @ResponseBody
    @ApiOperation(value = "文件上传", authorizations = @Authorization("TOKEN"))
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", required = true, paramType = "form", value = "Base64字符串")
            , @ApiImplicitParam(name = "appId", required = true, paramType = "form")})
    public ResultEntity<Long> saveBase64(@RequestParam("file") String file,
                                         @RequestParam("appId") String appId,
                                         @RequestParam("currentUserId") String currentUserId) throws BizException {

        MultipartFile multipartFile = new Base64MultipartFile(file);

        //遍历并保存文件
        if (multipartFile != null && multipartFile.getSize() > 0) {
            SysFile bean = new SysFile();
            //公共属性设置
            bean.setAppId(appId);
            bean.setUserId(currentUserId);
            bean.setSize(multipartFile.getSize());
            bean.setName(multipartFile.getOriginalFilename());
            bean.setType(getExtensionName(bean.getName()));
            bean.setContentType(multipartFile.getContentType());

            boolean saved = fileStorageAdapter.save(bean, multipartFile, "1");
            if (saved) {
                fileService.addBean(bean);
                return ResultEntity.success().setData(bean.getId());
            } else {
                return ResultEntity.failed("文件保存失败");
            }
        }

        return ResultEntity.failed("文件不能为空");
    }

    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }

}
